package com.ruoyi.framework.filter;

import com.ruoyi.common.util.request.RepeatedlyRequestWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Objects;

/**
 * Repeatable 防重复表单提交过滤器
 * 
 * @author ruoyi
 */
@Slf4j
public class RepeatableFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) {

    }

    /**
     * 将request转换为RepeatedlyRequestWrapper即requestWrapper类型
     * 是为了获取请求体的json表单参数
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        ServletRequest requestWrapper = null;
        if (request instanceof HttpServletRequest
                && StringUtils.startsWithIgnoreCase(request.getContentType(), MediaType.APPLICATION_JSON_VALUE)) {
            requestWrapper = new RepeatedlyRequestWrapper((HttpServletRequest) request, response);
        }
        if (Objects.isNull(requestWrapper)) {
            chain.doFilter(request, response);
        } else {
            chain.doFilter(requestWrapper, response);
        }
    }

    @Override
    public void destroy() {

    }
}
